package com.example.arithmeticleetcode.leetcode.September;

import java.util.*;

/**
 * @program: arithmetic-leetcode
 * @description:
 * @author: FangZhen
 * @create: 2020-09-10 09:31
 **/
public class Demo09 {

    public static void main(String[] args) {
        int[] deck = {1,2,3,4,4,3,2,1};
        System.out.println(hasGroupsSizeX(deck));

        System.out.println(new Demo09().hasGroupsSizeX2(deck));
    }

    public boolean hasGroupsSizeX2(int[] deck) {
        // 计数
        int[] counter = new int[10000];
        for (int num: deck) {
            System.out.println(counter[num]++);
        }

        // 求最大公约数
        return Arrays.stream(counter).reduce(this::gcd).getAsInt() > 1;
    }

    private int gcd(int a, int b) {
        return b == 0? a: gcd(b, a % b);
    }

    public static boolean hasGroupsSizeX(int[] deck) {

        if (deck.length == 1) {
            return false;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i : deck) {
            map.put(i, map.getOrDefault(i, 0) + 1);
        }
        int minValue = Integer.MAX_VALUE;
        for (Integer value : map.values()) {
            if (minValue > value) {
                minValue = value;
            }
        }
        for (Integer value : map.values()) {
            if (value % minValue != 0) {
                return false;
            }
        }
        return true;
    }
}
